<?php

namespace services\clinic;

use common\models\patient\User;
use common\components\Service;
use common\models\clinic\UserSurplus;
use Yii;

/**
 * Class UserSurplusService
 * @package services\clinic
 */
class UserSurplusService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return UserSurplus|null
     */
    public function findById(int $id = 0): ?UserSurplus
    {
        return UserSurplus::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return UserSurplus|null
     */
    public function findInfo(array $condition = []): ?UserSurplus
    {
        $query = UserSurplus::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = UserSurplus::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

//    /*
//     * 药品：美能甘草酸苷注射液（进口）
//      北大项目，输液大厅使用和购买这个药品的患者数据
//      字段：姓名、性别、年龄、手机号、诊疗号、诊室、购买量、使用量、剩余量、创建日期
//     */
//    public function statisticalDrug($project_id, $drug_id)
//    {
//        // 获取美能配置
//        $drugInfo = DrugConfig::find()
//            ->alias('a')
//            ->select(['b.drug_name', 'b.drug_unit','a.*'])
//            ->innerJoin(Drug::tableName(). ' b','b.id = a.drug_id')
//            ->where(['a.drug_id' => $drug_id])->asArray()->all();
//
//        $drugInfo = array_column($drugInfo,null,'id');
//        $config_id = array_column($drugInfo,'id');
//
//        ## 1. 先查询剩余量
//        $surplusInfo = User::find()
//            ->alias('a')
//            ->select([
//                'a.id',
//                'a.name',
//                "a.gender",
//                'a.patient_card_id',
//                'a.age',
//                'a.mobile',
//                'FROM_UNIXTIME( a.created_at ) AS created_at',
//                'c.`name` AS clinic_name',
//                'b.surplus_num',
//                'GROUP_CONCAT(b.surplus_num) as surplus_num_array',
//                'GROUP_CONCAT(b.drug_config_id) as drug_config_id_array',
//            ])
//            ->leftJoin(Clinic::tableName() . ' c','c.id = a.clinic_id')
//            ->innerJoin(DrugSurplus::tableName() . ' b', 'b.patient_user_id = a.id')
//            ->where([
//                'a.project_id' => $project_id,
//                'a.status' => 1,
//                'b.status' => 1,
//                'b.drug_config_id' => $config_id
//            ])
//            ->groupBy('a.id')
//            ->asArray()
//            ->all();
//
//        ## 2. 获取治疗量 剩余量 购买量
//        $recordInfo = User::find()
//            ->alias('a')
//            ->select([
//                'a.id',
//                'a.name',
//                "a.gender",
//                'a.patient_card_id',
//                'a.age',
//                'a.mobile',
//                'c.`name` AS clinic_name',
//                'FROM_UNIXTIME( a.created_at ) AS created_at',
//                'GROUP_CONCAT(b.type) as type_array',
//                'GROUP_CONCAT(b.drug_config_id) as drug_config_id_array',
//                'GROUP_CONCAT(b.operate_num) as operate_num_array',
//            ])
//            ->leftJoin(Clinic::tableName() . ' c','c.id = a.clinic_id')
//            ->innerJoin(DrugRecord::tableName() . ' b', 'b.patient_user_id = a.id')
//            ->where([
//                'a.project_id' => $project_id,
//                'a.status' => 1,
//                'b.drug_config_id' => $config_id,
//                'a.id' => 150351
//            ])
//            ->groupBy('a.id')
//            ->asArray()
//            ->all();
//
//        $excelData = [];
//        $waterType = [
//            '1' => '盐水',
//            '2' => '糖水'
//        ];
//        $genderArray = [
//            '0' => '不详',
//            '1' => '男',
//            '2' => '女',
//        ];
//
//        ## 3. 拼接数据
//        // 处理剩余
//        foreach ($surplusInfo as $value) {
//            $temp  = [
//                'name' => $value['name'],
//                'gender' => $genderArray[$value['gender']],
//                'age' => $value['age'],
//                'mobile' => $value['mobile'],
//                'patient_card_id' => $value['patient_card_id'],
//                'clinic_name' => $value['clinic_name'],
//                'created_at' => $value['created_at'],
//            ];
//            // 剩余量
//            $drug_config_id_array = explode(',', $value['drug_config_id_array']);
//            $surplus_num_array = explode(',', $value['surplus_num_array']);
//            $surplusStr = "";
//            foreach ($drug_config_id_array as $key => $config_id) {
//                $surplusStr .= $drugInfo[$config_id]['drug_name'] . $drugInfo[$config_id]['drug_volume'] . $drugInfo[$config_id]['drug_unit'] . '+' .$waterType[$drugInfo[$config_id]['water_type']] . $drugInfo[$config_id]['water_volume'] . 'ml';
//                $surplusStr .= " 剩余:" . $surplus_num_array[$key] . PHP_EOL;
//            }
//            $temp['surplus'] = $surplusStr;
//            $excelData[$value['id']] = $temp;
//        }
//        // 处理购买记录
//        foreach ($recordInfo as $value) {
//            // 判断是否追加数据
//            $temp = $excelData[$value['id']] ?? [];
//            if (empty($temp)) {
//                $temp = [
//                    'name' => $value['name'],
//                    'gender' => $genderArray[$value['gender']],
//                    'age' => $value['age'],
//                    'mobile' => $value['mobile'],
//                    'patient_card_id' => $value['patient_card_id'],
//                    'clinic_name' => $value['clinic_name'],
//                    'created_at' => $value['created_at'],
//                    'surplus' => ""
//                ];
//            }
//            $typeArray = explode(',',$value['type_array']);
//            $drug_config_id_array = explode(',',$value['drug_config_id_array']);
//            $operate_num_array = explode(',',$value['operate_num_array']);
//
//            $buyStr = '';
//            $useStr = '';
//            $quitStr = '';
//            $sumBuy = [];
//            $sumUse = [];
//            $sumQuit = [];
//
//            foreach ($typeArray as $key => $type) {
//                $config_id = $drug_config_id_array[$key];
//                $indexName = $drugInfo[$config_id]['drug_name'] . $drugInfo[$config_id]['drug_volume'] . $drugInfo[$config_id]['drug_unit'] . '+' .$waterType[$drugInfo[$config_id]['water_type']] . $drugInfo[$config_id]['water_volume'] . 'ml';
//                if ($type == 1) {
//                    $count = $sumBuy[$indexName] ?? 0;
//                    $sumBuy[$indexName] = $count + $operate_num_array[$key];
//                } elseif($type == 2) {
//                    $count = $sumUse[$indexName] ?? 0;
//                    $sumUse[$indexName] = $count + $operate_num_array[$key];
//                } elseif($type == 3) {
//                    $count = $sumQuit[$indexName] ?? 0;
//                    $sumQuit[$indexName] =$count + $operate_num_array[$key];
//                }
//            }
//
//            foreach ($sumBuy as $key => $buyCount) {
//                $buyStr .= $key . ' 新增' . $buyCount . PHP_EOL;
//            }
//            foreach ($sumUse as $key => $useCount) {
//                $useStr .= $key . ' 使用' . $useCount . PHP_EOL;
//            }
//            foreach ($sumQuit as $key => $quitCount) {
//                $quitStr .= $key . ' 退费' . $quitCount . PHP_EOL;
//            }
//
//            $temp['buy'] = $buyStr;
//            $temp['use'] = $useStr;
//            $temp['quit'] = $quitStr;
//            $excelData[$value['id']] = $temp;
//        }
//
//        // 通过excel 导出
//        $header = ['姓名','性别','年龄','手机号','诊疗号','诊室','创建日期','剩余量','购买量','使用量','退费量'];
//        ExcelHelper::exportExcel($header,$excelData,[
//            'name', 'gender', 'age', 'mobile', 'patient_card_id', 'clinic_name','created_at','surplus','buy', 'use', 'quit'
//        ]);
//
//    }

    /**
     * 治疗报表-治疗项目患者统计
     * @param array $params
     * @param int $drugConfigId
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getReportUserList(array $params, int $clinicProjectId, int $page, int $pageSize): array
    {
        $query = UserSurplus::find()->alias('us')
            ->select([
                'u.id', 'u.name', 'u.patient_card_id', 'u.age', 'u.gender', 'u.clinic_id',
                '(us.total_num + us.help_num) surplus_num',
            ])
            ->innerJoin(User::tableName().' u', 'u.patient_card_id = us.patient_card_id')
            ->where([
                'us.project_id' => Yii::$app->params['project_id'],
                'us.clinic_project_id' => $clinicProjectId,
                'u.project_id' => Yii::$app->params['project_id'],
                'u.status' => [User::STATUS_ENABLE, User::STATUS_INVALID],
            ]);
        if (isset($params['keywords']) && $params['keywords']) {
            $query->andWhere([
                'or',
                ['u.name' => $params['keywords']],
                ['u.patient_card_id' => $params['keywords']],
            ]);
        }
        if (isset($params['clinic_id']) && $params['clinic_id']) {
            $query->andWhere(['u.clinic_id' => $params['clinic_id']]);
        }
        if (isset($params['min_num']) && is_numeric($params['min_num'])) {
            $query->andHaving(['>=', 'surplus_num', $params['min_num']]);
        }
        if (isset($params['max_num']) && is_numeric($params['max_num'])) {
            $query->andHaving(['<=', 'surplus_num', $params['max_num']]);
        }
        $order = [
            'u.id' => SORT_ASC,
        ];
        $res = $this->getListPageRes($query, $page, $pageSize, $order);
        $res['list'] = $this->getReportUserListFormat($res['list'], $clinicProjectId);
        return $res;
    }

    /**
     * 格式化数据
     * @param array $data
     * @param int $clinicProjectId
     * @return array
     */
    public function getReportUserListFormat(array $data, int $clinicProjectId): array
    {
        $patientUserIds = array_column($data, 'patient_card_id');
        // 患者购买+治疗数量
        $patientNumMap = UserTreatmentService::getStatisticsList($patientUserIds, $clinicProjectId);
        // 诊室
        $clinicService = new ClinicService();
        $clinicMap = $clinicService->findList([
            'id' => array_column($data, 'clinic_id'),
            'indexBy' => 'id',
        ]);
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'patient_card_id' => $row['patient_card_id'],
                'age' => $row['age'],
                'gender_str' => User::$genders[$row['gender']] ?? '',
                'clinic_name' => $clinicMap[$row['clinic_id']]['name'] ?? '',
                'buy_num' => $patientNumMap[$row['patient_card_id']]['buy_num'] ?? 0,
                'treatment_num' => $patientNumMap[$row['patient_card_id']]['treatment_num'] ?? 0,
                'surplus_num' => $row['surplus_num'],
            ];
        }
        return $list;
    }

    /**
     * 数据导出，统计剩余308治疗数
     * @param $project_id
     * @param $clinicProject
     * @param array $params
     * @return array
     */
    public static function get308List($project_id, $clinicProject, array $params): array
    {
        $query = UserSurplus::find()
            ->select(['patient_card_id', 'SUM(total_num + help_num) 308_count'])
            ->where([
                'project_id' => $project_id,
                'clinic_project_id' => $clinicProject,
            ]);
        if (isset($select['laser_count_start']) && is_numeric($select['laser_count_start']) && isset($select['laser_count_end']) && is_numeric($select['laser_count_end'])) {
            $query->having(['between', '308_count', $params['laser_count_start'], $params['laser_count_end']]);
        }

        return $query
            ->indexBy('patient_card_id')
            ->groupBy('patient_card_id')
            ->asArray()
            ->all();
    }
}
